package com.springboot2.security.controller;

import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;


@Controller
public class ViewController {

    @ResponseBody
    @RequestMapping("/go")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, URISyntaxException {
//        response.setHeader("rs-api-id", "8HY9S5oj");
//        response.setHeader("rs-nonce", "5aWiAuj3K06U1kwE50v427dmIjWZouAu");
//        response.setHeader("rs-timestamp", "1552530598836");
//        response.setHeader("rs-sign", "506e712d5a24976ca7d9b948838adba4");
//        response.setHeader("username", "JSH452776448");
//        response.setHeader("password", "CQIVusvimlGFu4NvG3GLLA==");
//        try {
//            response.sendRedirect("http://www.impmacalline.com/api/saas/goLogin");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        CloseableHttpClient httpclient = HttpClients.custom()
                .setRedirectStrategy(new LaxRedirectStrategy())
                .build();
        try {
            HttpClientContext context = HttpClientContext.create();
            HttpGet httpGet = new HttpGet("http://httpbin.org/redirect/3");
            System.out.println("Executing request " + httpGet.getRequestLine());
            System.out.println("----------------------------------------");

            httpclient.execute(httpGet, context);
            HttpHost target = context.getTargetHost();
            List<URI> redirectLocations = context.getRedirectLocations();
            URI location = URIUtils.resolve(httpGet.getURI(), target, redirectLocations);
            System.out.println("Final HTTP location: " + location.toASCIIString());
        } finally {
            httpclient.close();
        }
    }
}